<template>
  <div class="app-container">


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
        v-if="!viewFlag"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="taskList"
    @selection-change="handleSelectionChange"
    highlight-current-row>
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考核指标描述" align="center" prop="assessmentCriteria" />
      <el-table-column label="成果形式" align="center" prop="assessmentForm" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

            <span style="margin-right: 10px;">
              <el-popover
                v-if="viewFlag"
                placement="right"
                title="指标信息"
                width="700"
                trigger="click"
              >
                <el-table :data="scope.row.sciTaskIndicatorsList || []" border>
                  <el-table-column label="一级指标类别" prop="firstLevel" align="center" />
                  <el-table-column label="二级指标分类" prop="secondLevel" align="center" />
                  <el-table-column label="三级指标明细" prop="thirdLevel" align="center" />
                  <el-table-column label="指标值" prop="indicatorValue" align="center" />
                </el-table>

                <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                slot="reference" >查看指标</el-button>
              </el-popover>
            </span>

            <el-button
              v-if="!viewFlag"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              v-if="!viewFlag"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>


        </template>


      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!--

     <div style="margin-top: 100px;">
    <el-divider > 产出指标</el-divider>
    <el-table :data="selectedIndicators" >
      <el-table-column label="一级指标类别" prop="firstLevel" align="center" />
      <el-table-column label="二级指标分类" prop="secondLevel" align="center" />
      <el-table-column label="三级指标明细" prop="thirdLevel" align="center" />
      <el-table-column label="指标值" prop="indicatorValue" align="center" />
    </el-table>
    </div> -->

    <!-- 添加或修改项目任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-card shadow="always" style="margin: 20px;">

         <el-divider><i class="el-icon-collection"></i> 任务信息</el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
              v-model="form.startTime"
              type="date"
              value-format="yyyy-MM-dd"
               style="width: 100%"
              placeholder="请选择任务开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
              v-model="form.endTime"
              type="date"
              value-format="yyyy-MM-dd"
               style="width: 100%"
              placeholder="请选择任务结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考核指标描述" prop="assessmentCriteria">
            <el-input v-model="form.assessmentCriteria" type="textarea" :rows="4" placeholder="请输入考核指标描述" />
          </el-form-item>
          <el-form-item label="成果形式" prop="assessmentForm">
            <el-input v-model="form.assessmentForm"  type="textarea" :rows="4" placeholder="请输入成果形式" />
          </el-form-item>
          <el-divider content-position="center">任务产出指标信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSciTaskIndicators">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSciTaskIndicators">删除</el-button>
            </el-col>
          </el-row>
          <el-table :data="sciTaskIndicatorsList" :row-class-name="rowSciTaskIndicatorsIndex" @selection-change="handleSciTaskIndicatorsSelectionChange" ref="sciTaskIndicators">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="一级指标类别" prop="firstLevel" width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.firstLevel" placeholder="请输入一级指标类别" />
              </template>
            </el-table-column>
            <el-table-column label="二级指标分类" prop="secondLevel" width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.secondLevel" placeholder="请输入二级指标分类" />
              </template>
            </el-table-column>
            <el-table-column label="三级指标明细" prop="thirdLevel" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.thirdLevel" placeholder="请输入三级指标明细" />
              </template>
            </el-table-column>
            <el-table-column label="指标值" prop="indicatorValue" width="200">
              <template slot-scope="scope">
                <el-input v-model="scope.row.indicatorValue" placeholder="请输入指标值" />
              </template>
            </el-table-column>

          </el-table>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/sci/projectTask";

export default {
  name: "ProjectTaskbak",
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
    viewFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSciTaskIndicators: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目任务表格数据
      taskList: [],
      // 任务产出指标表格数据
      sciTaskIndicatorsList: [],
      selectedIndicators: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        projectId: this.projectId,
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        startTime: null,
        endTime: null,
        assessmentCriteria: null,
        assessmentForm: null,
      },
      localIdCounter: 0, // 用于生成唯一的 localId
      // 表单参数
      form: {
        projectId: this.projectId,
      },
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "任务开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "任务结束时间不能为空", trigger: "blur" }
        ],
        assessmentCriteria: [
          { required: true, message: "考核指标描述不能为空", trigger: "blur" }
        ],
        assessmentForm: [
          { required: true, message: "考核形式不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    if(this.projectId !== null){
      this.getList();
    }else{
      this.loading=false;
    }
  },
  watch: {
    projectId(newVal) {
      if (newVal === null) {
        this.taskList = []; // 清空 taskList 数组
        this.queryParams.projectId = null; // 将 queryParams.projectId 设置为 null
        this.total = 0;
        return; // 如果 projectId 为 null，不执行任何操作
      }
      // 当 projectId 变化时，更新查询参数并重新获取列表
      this.queryParams.projectId = newVal;
      this.getList();
    }
  },
  methods: {
    /** 查询项目任务列表 */
   getList() {
      this.loading = true;
      console.log("taskQ:"+this.queryParams.projectId);
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;

        // 遍历 taskList 并为每个任务获取子信息
        const promises = this.taskList.map(task => {
          return getTask(task.id).then(subResponse => {
            // 假设 subResponse.rows 是子信息数组
            task.sciTaskIndicatorsList = [...subResponse.data.sciTaskIndicatorsList]; // 将子信息整合到对应的任务中
          }).catch(error => {
            task.sciTaskIndicatorsList = []; // 如果请求失败，可以赋空数组或其他默认值
          });
        });

        // 等待所有子任务请求完成
        Promise.all(promises).finally(() => {
          this.loading = false;
        });
        this.submitLocalData();
      }).catch(error => {
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        localId: null,
        projectId: null,
        taskName: null,
        startTime: null,
        endTime: null,
        assessmentCriteria: null,
        assessmentForm: null,
        status: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        isDeleted: null
      };
      this.sciTaskIndicatorsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetData() {
      this.reset();
      this.taskList = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 判断 row 是否是本地任务（是否有 localId）
      if (row.localId) {
        // 是本地任务，直接填充数据
        this.form = { ...row };
        this.sciTaskIndicatorsList = row.sciTaskIndicatorsList || [];
        this.form.localId = row.localId; // 保留原有 localId
      } else {
        // 已提交任务，从接口获取数据
        const id = row.id || this.ids;
        getTask(id).then(response => {
          this.form = response.data;
          this.sciTaskIndicatorsList = response.data.sciTaskIndicatorsList;
        });
      }

      this.open = true;
      this.title = "修改项目任务";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          const taskId = this.form.id; // 来自数据库的真实ID
          const localId = this.form.localId || `local-${this.localIdCounter++}`;

          const taskData = {
            ...this.form,
            sciTaskIndicatorsList: this.sciTaskIndicatorsList,
            localId: localId
          };

          let index = -1;

          if (taskId) {
            // 来自API的任务：根据 id 查找并更新
            index = this.taskList.findIndex(task => task.id === taskId);
          } else {
            // 本地任务：根据 localId 查找并更新
            index = this.taskList.findIndex(task => task.localId === localId);
          }

          if (index !== -1) {
            // 存在：更新已有任务
            this.taskList.splice(index, 1, taskData);
          } else {
            // 不存在：新增到表格底部
            this.taskList.push(taskData);
          }

          this.submitLocalData();

          // 关闭弹窗并重置表单
          this.open = false;
          this.reset();

          // if (this.form.id != null) {
          //   updateTask(this.form).then(response => {
          //     this.$modal.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addTask(this.form).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除项目任务名"' + row.taskName + '"的数据项？')
      .then(() => {
        // 从 taskList 中移除对应行
        const index = this.taskList.indexOf(row);
        if (index !== -1) {
          this.taskList.splice(index, 1); // 删除指定行
        }
        this.submitLocalData();
      })
      .catch(() => {
        // 用户取消删除
      });
    },



    submitLocalData() {
      // 将当前 taskList 发送给父组件
      this.$emit('update:taskData', this.taskList);
    },
	/** 任务产出指标序号 */
    rowSciTaskIndicatorsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 任务产出指标添加按钮操作 */
    handleAddSciTaskIndicators() {
      let obj = {};
      obj.firstLevel = "";
      obj.secondLevel = "";
      obj.thirdLevel = "";
      obj.indicatorValue = "";
      obj.createdBy = "";
      obj.createdTime = "";
      obj.updatedBy = "";
      obj.updatedTime = "";
      obj.isDeleted = "";
      this.sciTaskIndicatorsList.push(obj);
    },
    /** 任务产出指标删除按钮操作 */
    handleDeleteSciTaskIndicators() {
      if (this.checkedSciTaskIndicators.length == 0) {
        this.$modal.msgError("请先选择要删除的任务产出指标数据");
      } else {
        const sciTaskIndicatorsList = this.sciTaskIndicatorsList;
        const checkedSciTaskIndicators = this.checkedSciTaskIndicators;
        this.sciTaskIndicatorsList = sciTaskIndicatorsList.filter(function(item) {
          return checkedSciTaskIndicators.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSciTaskIndicatorsSelectionChange(selection) {
      this.checkedSciTaskIndicators = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
